package ru.ifmo.kis;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import ru.ifmo.kis.domain.OrderedProduct;
import ru.ifmo.kis.domain.Product;

/**
 *
 * @author ivan
 */
public class Algorithm {

    public static final double INITIAL_TEMPERATURE = 100.0;
    private List<OrderedProduct> solution;

    public Algorithm(List<OrderedProduct> initialSolution) {
        this.solution = initialSolution;
    }

    public int countChangeovers() {
        int changeovers = 0;
        for (int i = 1; i < solution.size(); i++) {
            if (!solution.get(i).equals(solution.get(i - 1))) {
                changeovers++;
            }
        }
        return changeovers;
    }

    public int countFailedDeadlines() {
        int fails = 0;
        for (OrderedProduct p : solution) {
            if (p.getFinishTime() > p.getOrder().getDeadline()) {
                fails++;
            }
        }
        return fails;
    }

    public double energy() {
        return countChangeovers() + countFailedDeadlines();
    }

    public void refreshProductionTime() {
        solution.get(0).setStartTime(0); //TODO current time
        for (int i = 1; i < solution.size(); i++) {
            if (solution.get(i).equals(solution.get(i - 1))) {
                solution.get(i).setStartTime(solution.get(i - 1).getFinishTime());
            } else {
                solution.get(i).setStartTime(solution.get(i - 1).getFinishTime() + Product.CHANGEOVER_TIME);
            }
        }
    }

    public List<OrderedProduct> neighbour() {
        List<OrderedProduct> neighbour = new ArrayList<OrderedProduct>(solution);
        Random rand = new Random();
        int index1 = rand.nextInt(solution.size() - 1);
        int index2 = index1 + 1;
        OrderedProduct temp = neighbour.get(index1);
        neighbour.set(index1, neighbour.get(index2));
        neighbour.set(index2, temp);
        return neighbour;
    }
}
